import { ref, reactive, onMounted, type Ref } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { ChannelItem } from "./type/channelTypes";
import { h } from "vue";
import channelForm from "../componentsForm/channelForm.vue";
// 导入getFormRules函数而不是setOriginalFormId
import { getFormRules } from "./rule/channelRules";
import { useUserStoreHook } from "@/store/modules/user";

export function useChannelTable(
  tableRef: Ref,
  lesseeId: number
  /* tenantName: string,
  dealerId: number */
) {
  const form = reactive({
    name: "",
    code: "",
    status: "",
    SearchTerm: "",
    OrderBy: "",
    zoneId: 0
  });
  const formRef = ref();
  const dataList = ref<ChannelItem[]>([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  // 添加区域列表响应式变量
  const _zoneOptions = ref<{ label: string; value: number }[]>([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 列表列定义
  const columns = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "频道号",
      prop: "No",
      width: 80
    },
    {
      label: "名称",
      prop: "Name",
      minWidth: 120
    },
    /* {
      label: "区域",
      prop: "ZoneName",
      minWidth: 120
    }, */
    {
      label: "限制类型",
      prop: "Restriction",
      minWidth: 100,
      formatter: row => {
        switch (row.Restriction) {
          case 0:
            return "无限制";
          case 1:
            return "同组成员";
          case 2:
            return "区内用户";
          default:
            return "未知";
        }
      }
    },
    {
      label: "进组权限",
      prop: "PowerLimit1",
      minWidth: 100,
      formatter: row => {
        switch (row.PowerLimit1) {
          case 0:
            return "无限制";
          case 1:
            return "同组成员";
          case 2:
            return "区内用户";
          default:
            return "未知";
        }
      }
    },
    {
      label: "发言权限",
      prop: "PowerLimit2",
      minWidth: 100,
      formatter: row => {
        switch (row.PowerLimit2) {
          case 0:
            return "无限制";
          case 1:
            return "同组成员";
          case 2:
            return "区内用户";
          default:
            return "未知";
        }
      }
    },
    {
      label: "PTT模式",
      prop: "PttMode",
      minWidth: 100,
      formatter: row => (row.PttMode === 0 ? "默认" : "自定义")
    },
    {
      label: "最大人数",
      prop: "MaxLimit",
      minWidth: 80,
      formatter: row =>
        row.MaxLimit === 0 ? "无限制" : row.MaxLimit.toString()
    },
    {
      label: "允许监听",
      prop: "CanMonitor",
      minWidth: 100,
      formatter: row => (row.CanMonitor ? "允许" : "不允许")
    },
    {
      label: "编码方式",
      prop: "Encoding",
      minWidth: 100,
      formatter: row => {
        switch (row.Encoding) {
          case 0:
            return "Speex";
          case 1:
            return "G.711";
          case 2:
            return "G.729";
          default:
            return "未知";
        }
      }
    },

    {
      label: "备注",
      prop: "Comment",
      minWidth: 120,
      hide: true // 默认隐藏备注列
    },
    {
      label: "操作",
      fixed: "right",
      minWidth: 180,
      slot: "operation"
    }
  ];

  // 获取、搜索频道列表
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      SearchTerm: form.SearchTerm,
      tenantId: lesseeId
      //zoneId: 5
    };
    console.log(params);
    http
      .get(changeHttpLink("/api/Channel"), {
        params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          dataList.value = res.Data.Items || [];
          pagination.total = res.Data.TotalCount || 0;
          console.log(res.Data.Items);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        console.log(err);
        message("接口暂时不可用，使用模拟数据", { type: "warning" });
      });
  }
  function openDialog(title: string, row: any = null) {
    const id = row?.Id ?? 0; // 修改为大写Id

    // 使用getFormRules获取带excludeId的表单规则
    const rulesWithExcludeId = getFormRules(id);

    // 使用正确的大写开头属性名
    const formInlineData = {
      id: row?.Id ?? 0,
      no: row?.No ?? 0,
      name: row?.Name ?? "",
      dealerId: useUserStoreHook()?.userId ?? 0,
      tenantId: lesseeId,
      zoneId: row?.ZoneId ?? 0,
      restriction: row?.Restriction ?? 0,
      powerLimit1: row?.PowerLimit1 ?? 0,
      powerLimit2: row?.PowerLimit2 ?? 0,
      pttMode: row?.PttMode ?? 0,
      maxLimit: row?.MaxLimit ?? 0,
      canMonitor: row?.CanMonitor ?? true,
      encoding: row?.Encoding ?? 0,
      encodingRate: row?.EncodingRate ?? 0,
      encodingBit: row?.EncodingBit ?? 0,
      comment: row?.Comment ?? ""
    };

    addDialog({
      title: `${title}频道`,
      props: {
        formInline: formInlineData,
        title: title,
        // 传递表单规则给组件
        rules: rulesWithExcludeId
      },
      width: "640px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(channelForm, {
          ref: formRef,
          formInline: formInlineData,
          title: title,
          // 传递表单规则给组件
          rules: rulesWithExcludeId
        }),

      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = formRef.value.getFormData(); // 使用getFormData方法获取最新表单数据
        function chores() {
          message(`您${title}了频道ID为【${curData.name}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              ...curData
            };
            console.log("创建频道表单", formData);
            if (title === "创建") {
              http
                .post(changeHttpLink("/api/Channel"), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                    console.log(res);
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            } else {
              http
                .request("put", changeHttpLink(`/api/Channel/${id}`), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            }
          }
        });
      }
    });
  }

  // 删除频道
  function handleDelete(row: ChannelItem) {
    loading.value = true;
    http
      .request("delete", changeHttpLink(`/api/Channel/${row.Id}`), {
        data: row.Id
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          message(`您删除了频道ID为${row.Id}的这条数据`, {
            type: "success"
          });
          onSearch();
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  // 批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => item.Id);

    ElMessageBox.confirm(
      `是否确认删除选中的${listIds.length}条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/Channel/batch-delete"), {
            data: { ids: listIds }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已删除选中的${listIds.length}条数据`, {
                type: "success"
              });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 分页大小变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    onSearch();
  }

  // 处理当前页变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 多选框变化
  function handleSelectionChange(val: ChannelItem[]) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  // 多选框反选
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  // 重置表单
  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  // 设备检测
  function deviceDetection() {
    return window.innerWidth <= 1024;
  }

  onMounted(() => {
    // 初始化加载数据
    onSearch();
    // 删除这行
    // getZoneList();
  });

  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
